import math
import simplejson
from pymongo import MongoClient,ASCENDING,DESCENDING
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger

#数据库
client = MongoClient("mongodb://172.19.198.27:27018")
testResult = client.testResult
data = testResult.data


def json_response(func):
    """
    A decorator thats takes a view response and turns it
    into json. If a callback is added through GET or POST
    the response is JSONP.
    """
    def decorator(request, *args, **kwargs):
        objects = func(request, *args, **kwargs)
        if isinstance(objects, HttpResponse):
            return objects
        try:
            data = simplejson.dumps(objects)
            if 'callback' in request.GET:
                # a jsonp response!
                data = '%s(%s);' % (request.GET['callback'], data)
                return HttpResponse(data, "text/javascript")
        except:
            data = simplejson.dumps(str(objects))
        return HttpResponse(data, "application/json")
    return decorator


def index(request):
    return render(request, 'index.html')

@json_response
def indexProjectData(request):
    #data.create_index([("testcompany",ASCENDING)],unique=True)
    data.create_index:{key:{testcompany:1},deprecated_unique:"testcompany"}
    ProjectName = data.distinct("testcompany") 
    ProjectNumber = {}
    for d in ProjectName:
        ProjectNumber[d]=data.count({"testcompany":d})
    ProjectNumber2 = sorted(ProjectNumber.items(), key=lambda item:item[1],reverse=True)
    Projectdata = []
    for d in ProjectNumber2:
        PsNm = data.find({"testcompany":d[0],"status":"通过"}).count()/d[1]
        PsNm2 = round(PsNm*10000,0)
        PsNm3 = round(PsNm*100,2)
        PsNm = str(PsNm3) + '%'
        PjNa = d[0]
        ProjectName = d[0][0:5]
        Projectdata = Projectdata + [{"PjNa":PjNa,"ProjectName":ProjectName,"ProjectNumber":d[1],"PassNumber":PsNm,"ProjectNumber2":PsNm2,"PsNm3":PsNm}]
    return Projectdata
    
def list(request):
    ProjectName = request.GET['ProjectName']
    ProjectData = data.find({"testcompany":ProjectName})
    ProjectNumber = data.count({"testcompany":ProjectName})
    PageNumber = math.ceil(ProjectNumber/50)
    num1 = request.GET.get('page')
    if num1 == None:
        newPage = 1
        num2 = 50
        num1 = 0
    else:
        newPage = int(request.GET.get('page'))
        num2 = int(num1) * 50
        num1 = (int(num1)-1) * 50
    previousPage = newPage - 1
    if (newPage == 1):
        previousPage = False
    nextPage = newPage + 1
    files = []
    i = num1 +1
    if (num2 > ProjectNumber):
        nextPage = False
        for d in ProjectData[num1:ProjectNumber]:
            address = d['province']+'/'+d['city']+'/'+d['district']     
            files = files + [{'siteID':d['siteID'],'address':address,'status':d['status'],'testuser':d['testuser'],'date':d['date'],'Number':i}]
            i=i+1
    else:        
        for d in ProjectData[num1:num2]:
            address = d['province']+'/'+d['city']+'/'+d['district']     
            files = files + [{'siteID':d['siteID'],'address':address,'status':d['status'],'testuser':d['testuser'],'date':d['date'],'Number':i}]
            i=i+1
    #paginator = Paginator(files,50,2)
    #page = request.GET.get('page')
    #try:
    #    customer = paginator.page(page)
    #except PageNotAnInteger:  #如果输入页码错误，就显示第一页
    #    customer = paginator.page(1)
    #except EmptyPage:   #如果超过了页码范围，就把最后的页码显示出来
    #    customer = paginator.page(paginator.num_pages)
    return render(request, 'list.html',{"files":files,"ProjectName":ProjectName,'PageNumber':PageNumber,'newPage':newPage,'nextPage':nextPage,'previousPage':previousPage})


def details(request):
    ProjectName = request.GET['ProjectName']
    return render(request, 'details.html',{"ProjectName":ProjectName})
